//
//  BIDUserSaveToInternet.m
//  depm
//
//  Created by Yeming on 13-5-4.
//  Copyright (c) 2013年 Yeming. All rights reserved.
//

#import "BIDUserSaveToInternet.h"
#import "BIDDatabaseManager.h"
#define kUserNameLabel 10
#define kLogInButton 11
#define kUpLoadFileOp 12
#define kDownLoadFileOp 13
#define kRestSize 14
#define kUpDoalKey @"key"
#define kActionView 15
#define kTableName @"payout.sqlite"
#define kDataName @"sightType3.text"
#define kFileNameKeys @"KPTestFile.text"
#define kUpDownTime @"time.text"
@interface BIDUserSaveToInternet ()
{
    BOOL isRestView;
    UILabel *timeLabel;
    BOOL _isWillView;

}
@property(copy,nonatomic) NSString *upTime;
@end

@implementation BIDUserSaveToInternet
@synthesize restSize,theUserName,restView,upLoadVieww,downLoadView;
@synthesize theUsed,theUsedName,upTime;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
      

     isRestView=NO;
     getUserInfo=[[KPGetUserInfoOperation alloc] initWithDelegate:self operationItem:nil];
     self.view.backgroundColor=[UIColor grayColor];
    [self initView];
	// Do any additional setup after loading the view.
}
-(void)viewDidUnload
{
    [self.restView release];
    [self.theUserName release];
    [self.downLoadView release];
    [self.upLoadVieww release];
    [timeLabel release];
    [super release];
    timeLabel=nil;
    self.theUserName=nil;
    self.upLoadVieww=nil;
    self.downLoadView=nil;
    self.restView=nil;
}
-(void)initView
{
    self.title=@"用户设置";
    UIBarButtonItem *bar=[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(backNext:)];
    self.navigationItem.leftBarButtonItem=bar;
    //user's head
    UIImageView *headImg=[[UIImageView alloc] initWithFrame:CGRectMake(40, 80, 100, 100)];
    headImg.image=[UIImage imageNamed:@"erping1.jpg"];
    [self.view addSubview:headImg];
    [headImg release];
    
    //login
    UIButton *login=[UIButton buttonWithType:UIButtonTypeCustom];
//    login.backgroundColor = [UIColor clearColor];
    login.frame=CGRectMake(60, 150, 200, 120);
     [login setTitle:@"登陆:" forState:UIControlStateNormal];
     [login setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
//     [login setAdjustsImageWhenDisabled:YES];
    
    [login setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
   // login.backgroundColor=[UIColor whiteColor];
    [login addTarget:self action:@selector(loginButton:) forControlEvents:UIControlEventTouchUpInside];
    login.tag=kLogInButton;
    [self.view addSubview:login];
    // user'name
    UILabel *userName1=[[UILabel alloc] initWithFrame:CGRectMake(140, 40, 100, 30)];
  
    userName1.textColor=[UIColor blackColor];
    userName1.backgroundColor=[UIColor grayColor];
    [userName1 textAlignment];
    userName1.tag=kUserNameLabel;
    UIFont *font=[UIFont fontWithName:@"Blazed"size:10 ];
     userName1.font=font;
    userName1.adjustsFontSizeToFitWidth=YES;
    userName1.hidden=YES;
    [self.view addSubview:userName1];
    //upLoadOpButton
    UIButton *upLoad=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    upLoad.frame=CGRectMake(160, 90, 100, 30);
    [upLoad setTitle:@"上传" forState:UIControlStateNormal];
    [upLoad setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    upLoad.tag=kUpLoadFileOp;
    upLoad.hidden=YES;
    [upLoad addTarget:self action:@selector(pressUpLoad:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:upLoad];
    //create downLoad
    UIButton *DownLoad=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    timeLabel=[[UILabel alloc] initWithFrame:CGRectMake(10, 90, 100, 60)];
    DownLoad.frame=CGRectMake(160, 140, 100, 30);
    [DownLoad setTitle:@"下载" forState:UIControlStateNormal];
    [DownLoad setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    DownLoad.tag=kDownLoadFileOp;
    DownLoad.hidden=YES;
    [DownLoad addTarget:self action:@selector(initAlterView:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:DownLoad];
    // create restSize buttom
    UIButton *restSize1=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    restSize1.frame=CGRectMake(0, 220, 320, 40);
    [restSize1 setTitle:@"剩余空间" forState:UIControlStateNormal];
    [restSize1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    restSize1.tag=kRestSize;
    [restSize1 addTarget:self action:@selector(pressRestSize:) forControlEvents:UIControlEventTouchUpInside];
    restSize1.hidden=YES;
    [self.view addSubview:restSize1];
    //action
    UIActivityIndicatorView *actionView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    actionView.frame=CGRectMake(160, 200, 50, 50);
    actionView.tag=kActionView;
    actionView.hidden=YES;
    
    [self.view addSubview:actionView];
    [actionView release];
    //name
    
    self.theUserName=[[UILabel alloc] initWithFrame:CGRectMake(50, 40, 40,30)];
    self.theUserName.textColor=[UIColor blackColor];
    self.theUserName.backgroundColor=[UIColor grayColor];
    self.theUserName.font=font;
    self.theUserName.text=@"用户名：";
    self.theUserName.adjustsFontSizeToFitWidth=YES;
    self.theUserName.hidden=YES;
    [self.view addSubview:self.theUserName];
    [self.theUserName release];
    
    //up and down load view
    
    self.upLoadVieww=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.upLoadVieww.frame=CGRectMake(170, 90, 50,50);
    self.upLoadVieww.hidden=YES;
    
    self.upLoadVieww.hidesWhenStopped=YES;
    [self.view addSubview:self.upLoadVieww];
    
    self.downLoadView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    self.downLoadView.frame=CGRectMake(170, 120, 60, 60);
    self.downLoadView.hidden=YES;

    self.downLoadView.hidesWhenStopped=YES;
    [self.view addSubview:self.downLoadView];
}
-(void)initRestInfoView
{
    //restSize1.frame=CGRectMake(0, 220, 320, 40);
    
    self.restView=[[UIView alloc] initWithFrame:CGRectMake(0, 270, 320, 150)];
    self.restView.backgroundColor=[UIColor whiteColor];
    self.theUsedName=[[UILabel alloc] initWithFrame:CGRectMake(310, 10, 50, 30)];
    self.theUsedName.text=@"使用％情况:";
    self.theUsedName.adjustsFontSizeToFitWidth=YES;
    self.theUsedName.textColor=[UIColor blackColor];
    [self.view addSubview:self.theUsedName];
    self.theUsed=[[UILabel alloc] initWithFrame:CGRectMake(50, 10, 50, 30)];
    self.theUsed.textColor=[UIColor blackColor];
    self.theUsed.adjustsFontSizeToFitWidth=YES;
    [self.restView addSubview:self.theUsed];
    NSArray *array=[self.restSize componentsSeparatedByString:@","];
    UILabel *total=[[UILabel alloc] initWithFrame:CGRectMake(30, 50, 200, 30)];
    total.text=[array objectAtIndex:0];
    UILabel *rest=[[UILabel alloc] initWithFrame:CGRectMake(30, 80, 200, 30)];
    rest.text=[array objectAtIndex:1];
    rest.textColor=[UIColor greenColor];
    
    UIButton *but=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    but.frame=CGRectMake(290, 10, 30, 30);
    

       [UIView animateWithDuration:1 animations:^{
        CGAffineTransform move=CGAffineTransformMakeTranslation(-305, 10);
        self.theUsedName.transform=move;
        
       [self.restView addSubview:self.theUsedName];

       } completion:^(BOOL finished){
           [self.restView addSubview:total];
           [total release];
           [self.restView addSubview:rest];
           [rest release];
          
       }
        ];
    
 
    
    [self.view addSubview:self.restView ];
    [self.restView release];
    
    
    
    
    
}
#pragma mark--button's event
-(void)loginButton:(UIButton*)button
{
    KPConsumer *consumer = [[KPConsumer alloc] initWithKey:@"xcInFxiv9tnMmS5a" secret:@"D7JvQn0wTR5rP9D9"];
    userIntoView = [[KPAuthController alloc] initWithConsumer:consumer];
    [self.navigationController pushViewController:userIntoView animated:YES];
    
}
-(void)pressRestSize:(UIButton*)button
{
    if (!self.restView) {
         [self initRestInfoView];
    }
   
    //NSLog(@"%@",self.restSize);
}
-(void)pressUpLoad:(UIButton*)button
{
    KPUploadFileOperationItem *item = [[KPUploadFileOperationItem alloc] init];
    NSString *filepath =[self ReadSqlFileName:kFileNameKeys];
    item.root = @"app_folder";
    
    //要上传到的文件夹必须已经创建，即hejinbo123文件夹必须已经存在,并且必须携带文件名
    item.path = @"KPTestFile.text";
    item.fileName = @"KPTestFile.text";
    item.fileData = [NSData dataWithContentsOfFile:filepath];
    item.isOverwrite = YES;
    
    _uploadFileOp = [[KPUploadFileOperation alloc] initWithDelegate:self operationItem:item];
    [_uploadFileOp executeOperation];
    [self hiddenOtherButton:button];
    [[NSUserDefaults standardUserDefaults] setValue:[self getCurrntTime] forKey:kUpDoalKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [item release];
    button.hidden=YES;
    self.upLoadVieww.hidden=NO;
    [self.upLoadVieww startAnimating];
}

-(NSString *)ReadSqlFileName :(NSString *)dbPathFile//dbPathFile参数接受的是#define kFileNameKey @"FMDBBaseA1.db"//的数据库名
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//找到文件的路径所在地
    NSString *documentDirectory = [paths objectAtIndex:0];
    NSString * dbPath = [documentDirectory stringByAppendingPathComponent:dbPathFile];
    return  dbPath;
}
-(void)pressDownLoad:(UIButton*)button
{
    KPFolderOperationItem *item = [[KPFolderOperationItem alloc] init];
    
    item.root = @"app_folder";
    //要下载的文件相对路径,并且必须携带文件名
   item.path = @"KPTestFile.text";
    //[[NSFileManager defaultManager] ];
   
    
    _downloadFileOp = [[KPDownloadFileOperation alloc] initWithDelegate:self operationItem:item];
    [_downloadFileOp executeOperation];

    [self hiddenOtherButton:button];
    [item release];
    button.hidden=YES;
    self.downLoadView.hidden=NO;
    [self.downLoadView startAnimating];

}
-(void)initAlterView:(UIButton*)button
{
    
   
    
        [self dispatchTwo];
  
    
}
-(void)dispatchTwo
{
    NSString *timeStr;
    UIAlertView *alter;
    if (upTime.length!=0) {
        timeStr=[NSString stringWithFormat:@"上次时间:%@",upTime];
        
        alter=[[UIAlertView alloc] initWithTitle:@"下载提示:" message:timeStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    else
    { timeStr=@"没有上传";
        alter =[[UIAlertView alloc] initWithTitle:@"温馨提醒" message:timeStr delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];}
    [alter show];
    [alter release];
    

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIButton *downLoad=(UIButton*)[self.view viewWithTag:kDownLoadFileOp];
    if (buttonIndex==1) {
        [self pressDownLoad:downLoad];
    }
}
#pragma mark--create file





#pragma mark--viewWill
-(void)viewWillAppear:(BOOL)animated
{
//       self.navigationController.navigationBarHidden = NO;

     if (userIntoView.isAlreadAuth)
    {
         UIButton *logIn=(UIButton *)[self.view viewWithTag:kLogInButton];
        UIActivityIndicatorView *actionView=(UIActivityIndicatorView* )[self.view viewWithTag:kActionView];
        logIn.hidden=YES;
        [actionView startAnimating];
        [getUserInfo executeOperation];
        [self downTime];
        _isWillView=YES;
    }
    else
    {
        NSLog(@"登陆失败");
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark--kuaipanDeletegate
-(void)operation:(KPOperation *)operation success:(id)data
{
    UIButton *upLoad=(UIButton*)[self.view viewWithTag:kUpLoadFileOp];
    UIButton *downLoad=(UIButton*)[self.view viewWithTag:kDownLoadFileOp];
     UIActivityIndicatorView *actionView=(UIActivityIndicatorView* )[self.view viewWithTag:kActionView];
    if (getUserInfo==operation) {
        UIButton *restButton=(UIButton*)[self.view viewWithTag:kRestSize];
      
        
        KPUserInfo *userInfo=data;
        UILabel *userName=(UILabel*)[self.view viewWithTag:kUserNameLabel];
        userName.text=userInfo.userName;
        if (_isWillView) {
            [actionView stopAnimating];
            restButton.hidden=NO;
            self.theUserName.hidden=NO;
            userName.hidden=NO;
            upLoad.hidden=NO;
            downLoad.hidden=NO;

        }
        
       
        self.restSize=[NSString stringWithFormat:@"总共：%lld kb,已使用:%lld kb",userInfo.quotaTotal/1000,userInfo.quotaUsed/1000];
        NSLog(@"%@",self.restSize);
       
        
        
    }
    if (_uploadFileOp==operation){
        [self upDownTime];
    }
    if (_uploadTime==operation) {
        [self downTime];
        _isWillView=NO;
      
    }
    if (_downloadFileOp==operation) {
        [self.downLoadView  stopAnimating];
        upLoad.hidden=NO;
        downLoad.hidden=NO;
        [[BIDDatabaseManager SharedOperator].fmdbDataBase close];
        NSString *documentsDirectory= [NSHomeDirectory()
                                        stringByAppendingPathComponent:@"Documents"];
        NSString *oldFile= [documentsDirectory
                            stringByAppendingPathComponent:kFileNameKeys];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:oldFile]){
              [[NSFileManager defaultManager] removeItemAtPath:oldFile error:nil];
            
            NSData *new=[NSData dataWithContentsOfFile:data];
                      [[NSFileManager defaultManager] createFileAtPath:oldFile contents:new attributes:nil];
        }
        else
        {
            NSData *new=[NSData dataWithContentsOfFile:data];
            [[NSFileManager defaultManager] createFileAtPath:oldFile contents:new attributes:nil];
        }
        
        if (![[BIDDatabaseManager SharedOperator].fmdbDataBase open]) {
            NSLog(@"ssss");
        }


        
    }
    if (_downloadTime==operation) {
        NSString *file=data;
        
        self.upTime=[NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
        
        
        [self.upLoadVieww stopAnimating];
        if (!_isWillView) {
            upLoad.hidden=NO;
            downLoad.hidden=NO;
            // [actionView stopAnimating];
        }
        
       
    }

    
}
#pragma mark---back
-(void)backNext:(id)send
{
         [self dismissViewControllerAnimated:YES completion:nil];

       UIView * view = self.navigationController.view;
       [self pageCurlAnmation:view];
       [self.navigationController popViewControllerAnimated:NO];

}
-(void)pageCurlAnmation:(UIView*)view
{
    CATransition *tran=[CATransition animation];
    tran.type=@"cube";//pageCurl／flip/cube
    tran.subtype=@"fromLeft";//fromRight
    tran.duration=3.0;
    tran.delegate=self;
    [view.layer addAnimation:tran forKey:@"ads"];
}
#pragma mark---hidden other button
-(void)hiddenOtherButton:(UIButton*)button
{
    UIButton *upLoad=(UIButton*)[self.view viewWithTag:kUpLoadFileOp];
    UIButton *downLoad=(UIButton*)[self.view viewWithTag:kDownLoadFileOp];
    if (button==upLoad) {
        downLoad.hidden=YES;
    }
    else
    {  upLoad.hidden=YES; }
    
    
    
}
-(NSString *)getCurrntTime
{
    NSDate* now = [NSDate date];
    NSDateFormatter *formaton=[[NSDateFormatter alloc] init];
    
    [formaton setDateFormat:@"YYYY-MM-dd HH:mm:ss +0800"];
    
    NSString *str=[formaton stringFromDate:now];
    NSArray *array=[str componentsSeparatedByString:@"+"];
    return [array objectAtIndex:0];
}


#pragma mark----upDown time
-(void)upDownTime
{
    KPUploadFileOperationItem *item = [[KPUploadFileOperationItem alloc] init];
    NSString *filepath =[self ReadSqlFileName:kUpDownTime];
    //    NSString *dd=@"ffdsfdasdsa";
    //    [dd writeToFile:filepath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    NSString *time=[self getCurrntTime];
    
    [time writeToFile:filepath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    item.root = @"app_folder";
    
    //要上传到的文件夹必须已经创建，即hejinbo123文件夹必须已经存在,并且必须携带文件名
    item.path = kUpDownTime;
    item.fileName =kUpDownTime;
    item.fileData = [NSData dataWithContentsOfFile:filepath];
    item.isOverwrite = YES;
    
    _uploadTime = [[KPUploadFileOperation alloc] initWithDelegate:self operationItem:item];
    [_uploadTime executeOperation];
    
}
-(void)downTime
{
    
    KPFolderOperationItem *item = [[KPFolderOperationItem alloc] init];
    
    item.root = @"app_folder";
    //要下载的文件相对路径,并且必须携带文件名
    item.path = kUpDownTime;
    //[[NSFileManager defaultManager] ];
    
    
    _downloadTime = [[KPDownloadFileOperation alloc] initWithDelegate:self operationItem:item];
    [_downloadTime executeOperation];

    
}


@end
